/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */

'use strict';

app.controller('dataGridCtrl',['$scope','uiGridConstants','$compile','dataFetcher','$state','$stateParams','$timeout','$animate',function($scope, uiGridConstants,$compile,dataFetcher,$state,$stateParams,$timeout,$animate) {

    $scope.myName = 'DataGrid';
    dataFetcher.registScope($scope);

    //$scope.resultData = {'list':[]}

   /*
    "index": 75,
    "type": "电视剧", 收视指数
    */

    $scope.gridOptions = {
        i18n: 'zh-cn',
        enableGridMenu: true,
        enableSorting: true,
        columnDefs: [
            {field: 'time', displayName: '时间周期',/*suppressRemoveSort: true, */enableColumnMenu: false, sort: {direction: uiGridConstants.DESC,priority: 0} ,enableHiding: false,width:120,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'programme', displayName: '名称', enableSorting: false, enableColumnMenu: false,enableHiding: false,width:120,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>' },
            {field: 'fullType', displayName: '类型', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'pv', displayName: '推及PV',/*suppressRemoveSort: true,*/ enableColumnMenu: false, sort: {direction: uiGridConstants.DESC,priority: 1},cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'uv', displayName: '推及UV', enableColumnMenu: false, sort: {direction: uiGridConstants.DESC,priority: 2},cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'norm', displayName: '收视指数',enableColumnMenu: false, sort: {direction: uiGridConstants.DESC,priority: 3},cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'superNorm', displayName: '优秀norm', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'maxNorm', displayName: '周最高指数', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'terminal', displayName: '终端', enableColumnMenu: false, sort: {direction: uiGridConstants.ASC,priority: 4},cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'channel', displayName: '渠道', enableColumnMenu: false, sort: {direction: uiGridConstants.ASC,priority: 5},cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'language', displayName: '语言', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'area', displayName: '地区', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'star', displayName: '明星', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'sex', displayName: '受众性别', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'age', displayName: '受众年龄', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'},
            {field: 'region', displayName: '受众地域', enableSorting: false, enableColumnMenu: false,cellTemplate:'<div class="ui-grid-cell-contents" title="{{COL_FIELD CUSTOM_FILTERS}}"> {{COL_FIELD CUSTOM_FILTERS}}</div>'}
        ],
        useExternalSorting: true,
        useExternalPagination: true,
        onRegisterApi: function (gridApi) {
            $scope.gridApi = gridApi;
            $scope.gridApi.core.on.sortChanged($scope, sortChanged);
            // 默认一开始按时间周期排序
            // sortChanged($scope.gridApi.grid, [ $scope.gridOptions.columnDefs[0] ] );
            //排序
            $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                paginationOptions.pageNumber = newPage;
                paginationOptions.paginationPageSize = pageSize;
                getPage();
            });


            $animate.enabled(gridApi.grid.element, false);
        },
        //data: 'resultData.list',
        paginationPageSizes: [50, 100, 200],
        paginationPageSize: 50,
        enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
        enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
        minRowsToShow:0,
        enableMinHeightCheck:false,
        enablePaginationControls:false,
        rowHeight:47
    };


    // 可以起到记住历史操作的作用
    var paginationOptions = {
        pageNumber: 1,
        paginationPageSize:50,
        sort: []
    };

    // 服务器排序
    var sortChanged = function (grid, sortColumns) {
        paginationOptions.sort = [];
        var tmpSort = [];
        for(var i=0;i<sortColumns.length;i++){
            var sortType = "";
            sortColumns[i].sort.priority = $scope.mzSortItems[sortColumns[i].field].priority-1;
            switch (sortColumns[i].sort.direction) {
                case uiGridConstants.ASC:
                    sortType = 'asc';
                    break;
                case uiGridConstants.DESC:
                    sortType = 'desc';
                    break;
                default:
                    break;
            }
            if(sortType=="")continue;
            tmpSort.push({'col':sortColumns[i].field,'order':sortType,'priority':sortColumns[i].sort.priority});
        }
        // tmpSort.sort(prioritySort);
        for(var i in tmpSort){
            paginationOptions.sort.push({'col':tmpSort[i].col,'order':tmpSort[i].order});
        }

        getPage();
    };

    // 服务器分页
    var getPage = function () {
        if(isPaginationPageSizeChange){
            paginationOptions.pageNumber = 1;
            isPaginationPageSizeChange = false;
        }
        var params = {
            'sort': paginationOptions.sort,
            'pageSize':paginationOptions.paginationPageSize,
            'pageNo':paginationOptions.pageNumber
        };
        dataFetcher.freshData($scope,params,$stateParams.type);

    };

    var isPaginationPageSizeChange = false;

    var initFenYe = function(){

        var fenYeButtonDraw = function(value){
            var _html = '';
            var totalPages = $scope.gridApi.pagination.getTotalPages();
            if(totalPages<=7){
                for(var i=1;i<=totalPages;i++){
                    if(i==value){
                        _html+='<button class="curbutton" ng-click="gridApi.pagination.seek('+i+')">'+i+'</button>';
                    }else{
                        _html+='<button ng-click="gridApi.pagination.seek('+i+')">'+i+'</button>';
                    }
                }
            }else{
                var showlow = value-2;
                var showhigh = value+2;

                if(showlow<1) showlow = 1;
                if(showhigh>totalPages)showhigh = totalPages;

                if(showlow>2){
                    _html+='<button ng-click="gridApi.pagination.seek('+1+')">'+1+'</button>&nbsp;&nbsp;...&nbsp;&nbsp;';
                }else if(showlow==2){
                    _html+='<button ng-click="gridApi.pagination.seek('+1+')">'+1+'</button>';
                }

                for(var i=showlow;i<=showhigh;i++){
                    if(i==value){
                        _html+='<button class="curbutton" ng-click="gridApi.pagination.seek('+i+')">'+i+'</button>'
                    }else{
                        _html+='<button ng-click="gridApi.pagination.seek('+i+')">'+i+'</button>'
                    }
                }

                if(showhigh<totalPages-1){
                    _html+='&nbsp;&nbsp;...&nbsp;&nbsp;<button ng-click="gridApi.pagination.seek('+totalPages+')">'+totalPages+'</button>';
                }else if(showhigh==totalPages-1){
                    _html+='<button ng-click="gridApi.pagination.seek('+totalPages+')">'+totalPages+'</button>';
                }
            }
            var ele = $compile(_html)($scope);
            angular.element('.pagesbuttons').html(ele);
        };

        //分页按钮
        $scope.$watch('gridOptions.paginationCurrentPage', function(value) {
            fenYeButtonDraw(value);
        });
        $scope.$watch(function(){return $scope.gridApi.pagination.getTotalPages();}, function(value) {
            // 为了触发分页按钮的重新分布
            if($scope.gridOptions.paginationCurrentPage!=1){
                $scope.gridOptions.paginationCurrentPage = 1;
                isPaginationPageSizeChange = true;
            }
            fenYeButtonDraw(1);
        });

        //$scope.gridApi.colMovable.moveColumn(0, 1);
    };


    $scope.initDom = function(){
        initFenYe();
    };

    //排序面板
    $scope.mzSortItems={
        'time':{displayName:'时间周期',sortType:-1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:1,isChecked:true},
        'pv':{displayName:'推及PV',sortType:-1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:2,isChecked:true},
        'uv':{displayName:'推及UV',sortType:-1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:3,isChecked:true},
        'norm':{displayName:'收视指数',sortType:-1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:4,isChecked:true},
        'terminal':{displayName:'终端',sortType:1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:5,isChecked:true},
        'channel':{displayName:'渠道',sortType:1,sortText:{"1":"升序(1,2,3...)","-1":"降序(3,2,1...)"},priority:6,isChecked:true}
    };


    $scope.checkedSortItem = function(name,type){
        if(type==1){
            $scope.mzSortItems[name].isChecked = !$scope.mzSortItems[name].isChecked;
        }else if(type==2){
            $scope.mzSortItems[name].sortType = 0-$scope.mzSortItems[name].sortType;
        }
    };

    $scope.changePriority = function(e,name,type){
        if(type==1){
            //上升
            if($scope.mzSortItems[name].priority==1)return;
            var el = angular.element(e.target);
            var curLi = el.parent().parent();

            var preName = curLi.prev().attr("data-mz-itemname");
            $scope.mzSortItems[preName].priority +=1;
            $scope.mzSortItems[name].priority -=1;

            curLi.prev().insertAfter(curLi);

        }else{
            if($scope.mzSortItems[name].priority==6)return;
            var el = angular.element(e.target);
            var curLi = el.parent().parent();

            var nextName = curLi.next().attr("data-mz-itemname");
            $scope.mzSortItems[nextName].priority -=1;
            $scope.mzSortItems[name].priority +=1;

            curLi.next().insertBefore(curLi);
        }

    };


    function prioritySort(x, y) {
        return (x.priority < y.priority) ? -1 : 1
    }

    $scope.$watch('mzSortItems', function(value,oldVal) {
        if(JSON.stringify(oldVal)==JSON.stringify(value))return;

        paginationOptions.sort = [];
        var tmpArr = [];
        for(var key in value){
            if(value[key].isChecked){
                tmpArr.push({'name':key,'sortType':value[key].sortType,'priority':value[key].priority});
            }else{
                $scope.gridOptions.columnDefs.forEach(function(obj){
                    if(obj.field==key){
                        obj.sort.direction = null;
                    }
                });
            }
        }
        tmpArr.sort(prioritySort);
        for(var i=0;i<tmpArr.length;i++){
            var tmpOrder = tmpArr[i].sortType==1?'asc':'desc';
            paginationOptions.sort.push({'col':tmpArr[i].name,'order':tmpOrder});

            //改变grid的表头排序箭头方向
            $scope.gridOptions.columnDefs.forEach(function(obj){
                if(obj.field==tmpArr[i].name){
                    obj.sort.direction = tmpOrder;
                }
            });
        }

        getPage();

    },true);


    $scope.dumpToExcel = function(){
        dataFetcher.dumpToExcelWithHistoryOptions();
    };


    $scope.$on('$viewContentLoaded',function(){
        // 排序组件
        $(".mz-datagrid-header .mz-sortbutton").off('click');
        $(".mz-datagrid-header .mz-sortbutton").on('click',function(e){
            /*if (e.stopPropagation)
             e.stopPropagation();
             else
             e.cancelBubble = true;*/

            $(".mz-sortpanel").toggle();
        });

        $(document).on('click',function(e){
            var e = e || window.event;
            var elem = e.target || e.srcElement;
            while (elem) { //循环判断至跟节点，防止点击的是div子元素
                if(elem.id=="mz-sort-panel"||elem.id=='mz-sort-panel-button'){
                    return;
                }
                elem = elem.parentNode;
            }
            $(".mz-sortpanel").hide();
        });


        $(".mz-item-priority img").on("mouseover",function(){
            var path = this.src;
            this.src = path.substring(0,path.length-4)+"Red.png";
        }).on("mouseout",function(){
            var path = this.src;
            this.src = path.substring(0,path.length-7)+".png";
        });

        $timeout(function(){
            $(' .ui-grid-header').setScroll({
                parentContrainer:$('.mz-datagrid-body'),
                gap: 0,
                prevBoxs:[$('.mz-res-filterbox .selectedItems-box')]
            });
        },1000);
    });

    $scope.isMzSortable = true;
}]);

